<?php

namespace App\Http\Controllers\Ceb;

use App\Models\ChannelProvider;
use App\Components\CebApiRequest;
use App\Constants\ChannelCheckStatus;
use App\Constants\ChannelOpenStatus;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Ceb\BaseController as Controller;
use App\Constants\CebApi;
use App\Models\Channel;
use App\Constants\ChannelSettlementStatus;

class ChannelController extends Controller
{
    
    public function __construct() {
        
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $int_ChannelProviderId = $request->get('channel_provider_id');
        $int_Page = $request->get('page', 1);
        $int_PageSize = $request->get('page_size', 10);
        $arr_Channel = Channel::where('channel_provider_id', $int_ChannelProviderId)->forPage($int_Page, $int_PageSize)->get();
        $int_ChannelCount = Channel::where('channel_provider_id', $int_ChannelProviderId)->count();
        $arr_ChannelCode = [];
        foreach ($arr_Channel as $mod_Channel) {
            $arr_ChannelCode[] = $mod_Channel->channel_code;
        }
        $request = new CebApiRequest();
        $res_Channel = $request->invoke(CebApi::CHANNEL_INFO, [
            'channel_code_list' => $arr_ChannelCode
        ]);
        $arr_ChannelDataList = $res_Channel->data('list');
        if ($arr_ChannelDataList != null) {
            $map_ChannelDataList = $this->mkmap($arr_ChannelDataList,'channel_code');
        }

        $arr_ChannelList = [];
        $map_CooperationCfg = config('cooperation');
        $map_TargetCfg = config('cooperation-target');
        $map_ContractType = config('contract-type');
        $map_CheckStatusCfg = config('channel-check');
        $map_OpenStatusCfg = config('channel-open');

        foreach ($arr_Channel as $mod_Channel) {
            $map_Channel = $mod_Channel->toArray();
            $map_Channel['channel_code'] = $mod_Channel->channel_code;
            $map_Channel['cooperation'] = $map_CooperationCfg[$mod_Channel->cooperation];
            $map_Channel['target'] = $map_TargetCfg[$mod_Channel->target];
            $map_Channel['contract_type'] = $map_ContractType[$mod_Channel->contract_type];
            $map_Channel['check_status'] = $map_CheckStatusCfg[$mod_Channel->check_status];
            $map_Channel['open_status'] = $map_OpenStatusCfg[$mod_Channel->open_status];
            if(isset($map_ChannelDataList[$mod_Channel->channel_code])){
                $map_Channel = array_merge($mod_Channel,$map_ChannelDataList[$mod_Channel->channel_code]);
            }else{
                $map_Channel['invest_num'] = 0;
                $map_Channel['invest_per'] = 0;
                $map_Channel['real_num'] = 0;
                $map_Channel['reg_num'] = 0;
                $map_Channel['reinvest_per'] = 0;
            }
            $arr_ChannelList[] = $map_Channel;
        }

        return $this->view('channel.index',[
            'channel_list' => $arr_ChannelList,
            'page' => $int_Page,
            'page_size' => $int_PageSize,
            'count' => $int_ChannelCount,
            'channel_provider_id' => $int_ChannelProviderId,
            'check_status' => $map_CheckStatusCfg,
            'open_status' => $map_OpenStatusCfg
        ]);
    }
    
    public function create(Request $request){
        $int_ChannelProviderId = $request->get('channel_provider_id');
        $mod_ChannelProvider = ChannelProvider::find($int_ChannelProviderId);
        $map_CooperationCfg = config('cooperation');
        $map_TargetCfg = config('cooperation-target');
        $map_ContractCfg = config('contract-type');
        return $this->view('channel.create',[
            'channel_provider' => $mod_ChannelProvider,
            'cooperation_list' => $map_CooperationCfg,
            'target_list' => $map_TargetCfg,
            'contract_list' => $map_ContractCfg
        ]);
    }
    
    public function store(Request $request){
        $arr_Cooperation = array_keys(config('cooperation'));
        $arr_Target = array_keys(config('cooperation-target'));
        $arr_ContactType = array_keys(config('contract-type'));
        $this->validate($request, [
            'channel_provider_id' => 'required|exists:channel_providers,id',
            'code' => 'required|string|between:2,10',
            'no' => 'required|numeric|multi_unique:code,channels,no,code',
            'cooperation' => 'required|in:' . implode(',',$arr_Cooperation),
            'target' => 'required|in:' . implode(',',$arr_Target),
            'start_date' => 'required|date',
            'end_date' => 'required|date',
            'contract_type' => 'required|in:' . implode(',',$arr_ContactType),
            'contract_amount' => 'required|numeric|min:1',
            'expections' => 'string'
        ]);
        $mod_ChannelProvider = ChannelProvider::find($request->channel_provider_id);
        $map_Params = $request->all();
        $map_Params['channel_provider_name'] = $mod_ChannelProvider->name;
        $map_Params['real_amount'] = 0;
        $map_Params['check_status'] = ChannelCheckStatus::NONE;
        $map_Params['open_status'] = ChannelOpenStatus::CLOSED;
        $map_Params['settlement_status'] = ChannelSettlementStatus::UNSETTLED;
        Channel::create($map_Params);
        return redirect('/ceb/channels/index?channel_provider_id=' . $request->channel_provider_id);
    }

    public function changeOpenStatus(Request $request){
        $arr_OpenStatus = array_keys(config('channel-open'));
        $this->validate($request,[
            'channel_id' => 'exists:channels,id',
            'status' => 'required|in:' . implode(',',$arr_OpenStatus)
        ]);
        $mod_Channel = Channel::find($request->channel_id);
        $int_OldStatus = $mod_Channel->open_status;
        $mod_Channel->open_status = $request->status;

        if(!$mod_Channel->save()){
            return $this->output(0,'修改失败！',[
                'old_status' => $int_OldStatus
            ]);
        }
        return $this->output(1,'成功');
    }

    public function check(Request $request){
        $mod_Channel = Channel::find($request->channel_id);
        $map_CooperationCfg = config('cooperation');
        $map_TargetCfg = config('cooperation-target');
        $map_ContractCfg = config('contract-type');
        $map_CheckStatus = config('channel-check');
        return $this->view('channel.check',[
            'channel' => $mod_Channel->toArray(),
            'cooperation_list' => $map_CooperationCfg,
            'target_list' => $map_TargetCfg,
            'contract_list' => $map_ContractCfg,
            'check_status' => $map_CheckStatus
        ]);
    }

    public function doCheck(Request $request){
        $arr_Cooperation = array_keys(config('cooperation'));
        $arr_Target = array_keys(config('cooperation-target'));
        $arr_ContactType = array_keys(config('contract-type'));
        $this->validate($request,[
            'id' => 'required|exists:channels,id',
            'code' => 'string|between:2,10',
            'no' => 'numeric',
            'cooperation' => 'in:' . implode(',',$arr_Cooperation),
            'target' => 'in:' . implode(',',$arr_Target),
            'start_date' => 'date',
            'end_date' => 'date',
            'contract_type' => 'in:' . implode(',',$arr_ContactType),
            'contract_amount' => 'numeric|min:1',
            'expections' => 'string',
            'check_status' => 'required|in:' . ChannelCheckStatus::PASS . ',' . ChannelCheckStatus::FAILED
        ]);
        $map_Data = $request->all();
        $mod_Channel = Channel::find($request->id);
        $mod_Channel->update($map_Data);
        return redirect('/ceb/channels/index?channel_provider_id=' . $mod_Channel->channel_provider_id);
    }

    public function settle(Request $request){
        $this->validate($request,[
            'id' => 'required|exists:channels,id',
            'pay_amount' => 'required|numeric|min:1',
            'mark' => 'string'
        ]);
        $mod_Channel = Channel::find($request->id);
        $map_Data = $request->all();
        $map_Data['settlement_status'] = ChannelSettlementStatus::SETTLED;
        if(!$mod_Channel->update($map_Data)){
            return $this->output(0,'失败!');
        }
        return $this->output(1,'成功');
    }

    public function show(Request $request){
        $mod_Channel = Channel::find($request->id);
        if(!$mod_Channel){
            return $this->output(0,'指定的渠道不存在!');
        }
        return $this->output(1,'',$mod_Channel);
    }

    public function daily(Request $request){
        $this->validate($request,[
            'channel_id' => 'required|exists:channels,id',
            'start_time' => 'date',
            'end_time' => 'date',
            'page' => 'integer',
            'page_size' => 'integer'
        ]);
        $mod_Channel = Channel::find($request->channel_id);
        $ceb_Request = new CebApiRequest();
        $map_Data = [
            'channel_code' => $mod_Channel->channel_code,
            'start_time' => strtotime($request->get('start_time',0)),
            'end_time' => strtotime($request->get('end_time',0)),
            'page' => strtotime($request->get('page',1)),
            'page_size' => $request->get('page_size',10)
        ];
        $res_Daily = $ceb_Request->invoke(CebApi::CHANNEL_DAILY,$map_Data);
        $int_Count = $res_Daily->data('count');
        $arr_List = $res_Daily->data('list');
        return $this->view('channel.daily',[
            'count' => $int_Count ? $int_Count : 0,
            'size' => $map_Data['page_size'],
            'page' => $map_Data['page'],
            'list' => $arr_List ? $arr_List : [],
            'channel_id' => $mod_Channel->id
        ]);
    }
}
